package com.zhn;

//实现Integer.parseInt()函数，将字符串转移成数字

public class StringToInt {
    public static int strToInt(String s) throws Exception {
        if(s.charAt(0) != '-'){
            return strToBInt(s);
        }else {
            //为负数先转后序的字符串，再赋值成负数
            String str = s.substring(1);
            int i = strToBInt(str);
            int res = -i;
            return res;
        }
    }
    public static int strToBInt(String str) throws Exception {
        if(str.length() > 32)
            throw new Exception("数字过长");

        int res =  0;
        int lenA = str.length()-1;
        char[] chars = str.toCharArray();
        for(char c: chars){
            if(c < '0' || c > '9'){
                throw new IllegalStateException("非法字符,无法转化");
            }
        }
        for(int i = 0; i < chars.length; i++){
            int temp = 1;
            int t = lenA;
            //表示该字符的位数，是百位还是千位。。。
            while(t-->0){
                temp*=10;
            }
            lenA-=1;
            res +=  (chars[i] - '0') * temp;
        }
        return res;
    }

    public static void main(String[] args) throws Exception {
        String a = "-123444";
        int i = strToInt(a);
        System.out.println(i);
    }
}
